package net.example.activity.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.oraycn.esbasic.helpers.StringHelper;

import net.example.manager.ClientGlobalCache;
import net.example.model.GGUser;
import net.example.model.UserBasicModel;
import net.example.ggtalk.R;
import net.example.utils.HeadImgHelper;

import java.util.List;

public class UserBasicAdapter extends BaseAdapter {
    private List<UserBasicModel> userList;
    private Context context;

    public UserBasicAdapter(List<UserBasicModel> userList, Context context)
    {
        this.context=context;
        this.userList=userList;
    }
    @Override
    public int getCount() {
        return this.userList.size();
    }

    @Override
    public Object getItem(int position) {
        return this.userList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {
        try {
            UserBasicAdapter.ViewHolder holder;
            if (view == null) {
                view = LayoutInflater.from(context).inflate(
                        R.layout.item_user, parent, false);
                holder = new UserBasicAdapter.ViewHolder(view);
                view.setTag(holder);
            } else {
                holder = (UserBasicAdapter.ViewHolder) view.getTag();
            }
            UserBasicModel user = this.userList.get(position);
            //user.getHeadImageUrl() == 0 表示头像为赋值
            if (user.getHeadImageUrl() == 0) {
                GGUser GGUser = ClientGlobalCache.getInstance().getUser(user.getUserID());
                HeadImgHelper.setUserHeadImg(holder.headerImg, GGUser);
            } else if (user.getHeadImageUrl() > 0) {
                holder.headerImg.setImageResource(user.getHeadImageUrl());
            }else {
                holder.headerImg.setVisibility(View.INVISIBLE);
            }
            holder.userName.setText(StringHelper.isNullOrEmpty((user.getDisplayName())) ? user.getUserName() : user.getDisplayName());
            holder.checkBox.setChecked(user.getChecked());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return view;
    }

    private class ViewHolder
    {
        public ImageView headerImg;
        public TextView userName;
        public CheckBox checkBox;

        public ViewHolder(View view)
        {
            this.headerImg= (ImageView) view.findViewById(R.id.image);
            this.userName=(TextView) view.findViewById(R.id.text);
            this.checkBox=(CheckBox)view.findViewById(R.id.checkbox);
        }
    }
}
